import axios from 'axios'
// import { Message,Loading } from 'element-ui';
import qs from 'qs';
import {MD5} from "./md5"

const cacheRequest = {} // 缓存请求

// 设置baseURL
//axios.defaults.baseURL = '/api'
//设置默认请求头
axios.defaults.headers = {
    'X-Requested-With': 'XMLHttpRequest'
}
// 设置请求过期时间 单位ms
axios.defaults.timeout = 3*60*1000
 
//请求拦截器
axios.interceptors.request.use(config => {
    config.headers = {
        ...config.headers,
        'token': localStorage.getItem('token'),
        Authorization:"Bearer " + localStorage.getItem("accessToken")
    }
    return config
}, error => {
    return Promise.reject(error)
})


//响应拦截器即异常处理
axios.interceptors.response.use(response => {
        return response.data
}, error => {
    let msg = error.response && error.response.data &&  error.response.data.message
    // Message.error(msg || error.message)
    return Promise.reject(error)
})

function getRequestKey(url,params,method){
    return MD5(JSON.stringify({url,params,method}))
}

function paramsFormat(params){
    if(typeof params !== "object"){
        return params;
    }
    for(let k in params){
        if(Array.isArray(params[k])){
            params[k] = params[k] + '';
        }
    }
    return params;
}

// 暂未实现
const Loading = function(){}

let  loadingInstance;

function showLoading(options){
    let params = ""
    if(typeof options == "string" || !options){
        params = {
            lock: true,
            text: options || '处理中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.15)'
        }
    }else{
        params = options
    }
    loadingInstance = Loading.service(params);
}
function closeLoading(){
    loadingInstance && loadingInstance.close();
}

const get = (url,params,loading=false)=>{
    let key = getRequestKey(url,params,'get')
    if(cacheRequest[key]){
        return cacheRequest[key]
    }
    if(loading){
        showLoading()
    }
    params = paramsFormat(params)
    return cacheRequest[key] = axios.get(url,{params}).finally(()=>{
        if(loading){
            closeLoading()
        }
        cacheRequest[key] && delete cacheRequest[key]
    })
}
const postJson = (url,params,loading=false)=>{
    let key = getRequestKey(url,params,'postJson')
    if(cacheRequest[key]){
        return cacheRequest[key]
    }
    if(loading){
        showLoading()
    }
    return cacheRequest[key] = axios.post(url,params).finally(()=>{
        if(loading){
            closeLoading()
        }
        cacheRequest[key] && delete cacheRequest[key]
    })
}

const put = (url,params,loading=false)=>{
    let key = getRequestKey(url,params,'put')
    if(cacheRequest[key]){
        return cacheRequest[key]
    }
    if(loading){
        showLoading()
    }
    return cacheRequest[key] = axios.put(url,params).finally(()=>{
        if(loading){
            closeLoading()
        }
        cacheRequest[key] && delete cacheRequest[key]
    })
} 

const del = (url,params,loading=false)=>{
    let key = getRequestKey(url,params,'del')
    if(cacheRequest[key]){
        return cacheRequest[key]
    }
    if(loading){
        showLoading()
    }
    return cacheRequest[key] = axios.delete(url,{params}).finally(()=>{
        if(loading){
            closeLoading()
        }
        cacheRequest[key] && delete cacheRequest[key]
    })
}

const post = (url,params,loading=false)=>{
    let key = getRequestKey(url,params,'post')
    if(cacheRequest[key]){
        return cacheRequest[key]
    }
    // params = paramsFormat(params);
    if(loading){
        showLoading()
    }
    return cacheRequest[key] = axios({
        method:"post",
        url:url,
        data:qs.stringify(params,{ indices: false }), // indices: false 数组 格式 list=1&list=2
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    }).finally(()=>{
        if(loading){
            closeLoading()
        }
        cacheRequest[key] && delete cacheRequest[key]
    })
} 
const postForm = (url,params)=>{
    return axios({
        method:"post",
        url:url,
        data:params,
        headers: {
            'Content-Type': 'multipart/form-data',
        }
    })
} 

const getExcelTemplate = (url,name)=>{
    const link = document.createElement('a')
    axios({
      method: "get",
      url: url,
      responseType: "blob",
    })
    .then((res) => {
      // 创建Blob对象，设置文件类型
      let blob = new Blob([res], {type: "application/vnd.ms-excel"})
      let objectUrl = URL.createObjectURL(blob) // 创建URL
      link.href = objectUrl
      link.download = name // 自定义文件名
      link.click() // 下载文件
      URL.revokeObjectURL(objectUrl); // 释放内存
    })
}

export default {
    get,
    post,
    postJson,
    postForm,
    put,
    delete:del,
    showLoading,
    closeLoading,
    getExcelTemplate
}